﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Fish.Models;
using Fish.DAL;
using Microsoft.AspNet.Identity;
using System.Security.Cryptography;
using System.Web.Security;

namespace Fish.Controllers
{
    /*Class used to handle the creation and editing of events.
     */
    [Authorize]
    public class EventsController : Controller
    {
        private FishContext db = new FishContext();

        // GET: /Events/
        public ActionResult Index()
        {
            return RedirectToAction("AccessDenied", "Error");
            return View(db.Events.ToList());
        }

        // GET: /Events/Details/5
        public ActionResult Details(int? id)
        {
            return RedirectToAction("AccessDenied", "Error");
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Events events = db.Events.Find(id);
            if (events == null)
            {
                return HttpNotFound();
            }
            return View(events);
        }
        // [Authorize]
        // GET: /Events/Create
        public ActionResult Create()
        {
            int userIdparsed = int.Parse(Session["userID"].ToString());

            List<Templates> shownTemplates = db.Templates.Where(t => t.UsersID == userIdparsed || t.UsersID == null).ToList();
            List<SelectListItem> selectTemp = new List<SelectListItem>();
            for (int i = 0; i < shownTemplates.Count(); i++)
            {
                if (Session["eventTemplate"] != null)
                {
                    if (shownTemplates[i].ID.ToString() == Session["eventTemplate"].ToString())
                    {
                        selectTemp.Add(new SelectListItem { Text = shownTemplates[i].Name, Value = shownTemplates[i].ID.ToString(), Selected = true });
                        Session["eventTemplate"] = null;
                    }
                    else
                    {
                        selectTemp.Add(new SelectListItem { Text = shownTemplates[i].Name, Value = shownTemplates[i].ID.ToString() });
                    }
                }
                else
                {
                    selectTemp.Add(new SelectListItem { Text = shownTemplates[i].Name, Value = shownTemplates[i].ID.ToString() });

                }
            }

            //  System.Diagnostics.Debug.WriteLine(selectTemp.Where(t => t.Value == Session["eventTemplate"].ToString()).First().Selected);

            ViewBag.TemplatesID = selectTemp;

            Events tempEvent = new Events();

            if (Session["eventName"] != null)
            {
                tempEvent.Name = Session["eventName"].ToString();
                Session["eventName"] = null;

            }


            if (Session["eventPrivacy"] != null)
            {
                tempEvent.PrivacyType = int.Parse(Session["eventPrivacy"].ToString());
                Session["eventPrivacy"] = null;
            }




            return View(tempEvent);
        }


        public int GetLoggedInID()
        {
            int id = -1;

            if (Session != null)
            {
                if (Session["userID"] != null)
                {
                    id = int.Parse(Session["userID"].ToString());
                }
            }

            else
            {
                if (User.Identity.IsAuthenticated)
                {
                    System.Diagnostics.Debug.WriteLine("feeh name");
                    string username = User.Identity.GetUserName();
                    Users us = db.Users.Where(u => u.Username.Equals(username)).FirstOrDefault();
                    id = us.ID;
                }
                else
                {
                    id = -1;
                    FormsAuthentication.SignOut();
                    RedirectToAction("Index", "Home");
                }
            }
            return id;
        }
        // POST: /Events/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        //[Authorize]
        public ActionResult Create(Events events)
        {

            if (ModelState.IsValid)
            {
                events.customStrings = new List<customizedString>();
                for (int i = 0; i < db.Templates.Find(events.TemplatesID).Customized.Count(); i++)
                {
                    for (int j = 0; j < db.Templates.Find(events.TemplatesID).Customized.ElementAt(i).fieldTitle.Count();j++ )
                    {
                        customizedString temp = new customizedString();
                        temp.text = "empty";
                        temp.tabNumber = i;
                        events.customStrings.Add(temp);

                    }
                }
                db.SaveChanges();
                db.Events.Add(events);
                EventUserRelations eur = new EventUserRelations();
                eur.EventsID = events.ID;
                eur.UsersID = GetLoggedInID();
                eur.IsAdmin = true;
                db.EventUserRelations.Add(eur);
                db.SaveChanges();
                //return RedirectToAction("Index");
                Session["eventTemplateID"] = events.TemplatesID;
                Session["eventID"] = events.ID;

                return RedirectToAction("Create", "EventInfo");

            }
            if (Session["userID"] != null)
            {
                int userIdparsed = int.Parse(Session["userID"].ToString());
                List<Templates> shownTemplates = db.Templates.Where(t => t.UsersID == userIdparsed || t.UsersID == null).ToList();
                ViewBag.TemplatesID = new SelectList(shownTemplates, "ID", "Name", events.TemplatesID);

            }
            else
            {
                return RedirectToAction("Create", "EventInfo");
            }



            


           


        return View(events);

        }


        public void CreateTemplate(String events)
        {
            //Session["event"] = events;
            System.Diagnostics.Debug.WriteLine(events);
            //   return RedirectToAction("Create", "Templates");


        }
        // GET: /Events/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return RedirectToAction("PageNotFound", "Error");

                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Events events = db.Events.Find(id);
            if (events == null)
            {
                return RedirectToAction("Expired", "Error");

                return HttpNotFound();
            }
            ViewBag.TemplatesID = new SelectList(db.Templates, "ID", "Name", events.TemplatesID);
            return View(events);
        }

        // POST: /Events/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "ID,Name,PrivacyType,Created,Modified,TemplatesID")] Events events)
        {
            if (ModelState.IsValid)
            {
                db.Entry(events).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.TemplatesID = new SelectList(db.Templates, "ID", "Name", events.TemplatesID);
            return View(events);
        }

        // GET: /Events/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return RedirectToAction("PageNotFound", "Error");

                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Events events = db.Events.Find(id);
            if (events == null)
            {
                return RedirectToAction("Expired", "Error");

                return HttpNotFound();
            }
            return View(events);
        }

        // POST: /Events/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Events events = db.Events.Find(id);
            db.Events.Remove(events);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        //Redirects to the template creation page after adding event name and privacy into the session
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult createTemplate(String eventName, int eventPrivacy)
        {
            Session["eventName"] = eventName;
            Session["eventPrivacy"] = eventPrivacy;
            System.Diagnostics.Debug.WriteLine(eventPrivacy);
            return Json(new { redirectToUrl = Url.Action("Create", "Templates") });
        }
    }
}
